<!--二次封装表单自定义组件-->
<template>
  <div class="hyForm" v-loading="loading" element-loading-background="rgba(255, 255, 255, 0.5)" v-bind:style="{ width: formWidth, margin :formMarrgin, overflow: 'hidden'}" >
    <el-form :model="value" ref="formData" status-icon :inline="inline" :inline-message="inline" :rules="yxyz" :size="size" :label-position="labelPosition" :label-width="labelWidth" class="demo-dynamic">
      <el-row :gutter="gutter">
        <el-col :span="col == 1 ? 24 : (col == 2 ? 12 : (col == 3 ? 8 : (col == 4 ? 6 : (col == 6 ? 4 : 24))))" v-for="(item, index) in formTitleData" :key="index" class="yy-form-col">
          <pop-form @focus="callback(item)" :item="item" v-if="formData[item.name] !== undefined" :value="formData[item.name]"  @input="handleInput($event,item.name)" :disabledAll="disabled"></pop-form>
        </el-col>
        <el-upload
          v-if="upload"
          class="upload-demo"
          action="/api/oss/ossAttach/upload"
          :headers ="{authorization:$Http.Getcok('token')}"
          :data="{type : types, areaCode: areaCode}"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :on-success="handleAvatarSuccess"
          :before-remove="beforeRemove"
          multiple
          :limit="3"
          :on-exceed="handleExceed"
          :file-list="fileList">
          <el-button size="small" type="primary">点击上传图片</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
        </el-upload>
      </el-row>
      <div v-bind:style="{ textAlign: buttonAlign}" >
        <el-button v-bind:style="{ width: buttonWidth}" v-if="button.save" :type="buttonProperty.save.type" @click="save()">{{buttonProperty.save.text}}</el-button>
        <el-button v-bind:style="{ width: buttonWidth}" v-if="button.rest" :type="buttonProperty.confirm.type" @click="restForm()">{{buttonProperty.rest.text}}</el-button>
        <el-button v-bind:style="{ width: buttonWidth}" v-if="button.confirm" :type="buttonProperty.confirm.type" @click="submitForm()">{{buttonProperty.confirm.text}}</el-button>
        <el-button v-bind:style="{ width: buttonWidth}" v-if="button.print" :type="buttonProperty.print.type" @click="print()">{{buttonProperty.print.text}}</el-button>
      </div>
    </el-form>
  </div>
</template>
<script>
/*
  v-model绑定的是表单的data 必穿
  :formTitle 定义表单数据必穿
  :button 定义表单按钮必传 {confirm: true, add: true, edit: true, close: true, rest: true}
  :buttonProperty 表单按钮自定义选填 {confirm: {type: 'primary', icon: '', round: false, circle: false, plain: false, txet: '确定'}, add: {type: 'primary', icon: '', round: false, circle: false, plain: false, text: '确定'}, edit: {type: 'primary', icon: '', round: false, circle: false, plain: false, text: '确定'}, close: {type: 'primary', icon: '', round: false, circle: false, plain: false, text: '确定'}, rest: {type: '', icon: '', round: false, circle: false, plain: false, text: '重置'}}
  :rules 验证规则  element ui相同写法
  @confirm  @edit @add @close @rest对应每个按钮事件 ， 其中 confirm 是确定按钮返回值为一个对象{state: 布尔值, data: 和v-model相同} ，rest会重置表单并且会返回v-model相同的值给调用的方法
  labelPosition 传入String类型 label对其方式  center  left  right
  labelWidth  传入String类型   label宽度
  size 表单大小类型 传入String
  col 传入1或者2 1列或者2列
  inline element ui的 传入布尔值 石否为块级显示
  gutter 左右布局的间距 默认20
  formWidth 表单宽度 默认100%
  buttonWidth 按钮宽度默认auto
  formMarrgin 表单marggin原生属性默认 auto
*/
// import rulesMain from '../validationRules/main'
export default {
  name: 'hyForm',
  props: {
    value: {
      type: [Array, Object],
      required: true,
      default: () => { return {} }
    },
    formTitle: {
      type: [Array, Object],
      required: true,
      default: () => { return {} }
    },
    upload: {
      type: Boolean,
      default: false
    },
    types: {
      type: [String, Number],
      default: 1
    },
    button: {
      type: [Array, Object],
      required: true,
      default: () => { return {confirm: false, add: false, edit: false, close: false, rest: false} }
    },
    buttonProperty: {
      type: [Array, Object],
      default: () => { return {confirm: {type: 'primary', text: '提交'}, rest: {type: '', text: '重置'}, save: {type: '', text: '保存'}, print: {type: 'primary', text: '确认'}} }
    },
    buttonRules: {
      type: Boolean,
      default: true
    },
    rules: {
      type: [Array, Object],
      default: () => { return {} }
    },
    labelPosition: {
      type: String,
      default: 'left'
    },
    labelWidth: {
      type: String,
      default: '100px'
    },
    size: {
      type: String,
      default: 'small'
    },
    col: {
      type: [String, Number],
      default: 1
    },
    gutter: {
      type: Number,
      default: 20
    },
    inline: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    },
    formWidth: {
      type: String,
      default: '100%'
    },
    buttonWidth: {
      type: String,
      default: 'auto'
    },
    buttonAlign: {
      type: String,
      default: 'center'
    },
    formMarrgin: {
      type: String,
      default: 'auto'
    }
  },
  components: {
  },
  data () {
    return {
      yxyz: this.rules,
      formData: {},
      formTitleData: [],
      loading: false,
      areaCode: '',
      fileList: []
    }
  },
  computed: {
    referrer () {
      return this.store.getters.getReferrer
    }
  },
  created () {
    this.formTitleData = this.formTitle
    // this.areaCode = this.tokenData.areaCode
    // this.getValue()
  },
  mounted () {
    this.getValue()
  },
  methods: {
    handleInput (val, key) {
      // val = val.replace(/^\s+|\s+$/g,"")
      // val = val.trim()
      // 去除所有空格
      if (typeof val === 'string') {
        // val = val.replace(/\s+/g, '')
        val = val.replace(/^\s+|\s+$/g, '')
      }
      this.value[key] = val
      // this.$emit('input', this.value)
      this.$emit('input', { ...this.value, [key]: val })
    },
    callback (item) {
      if (item.callback) {
        this.$emit('clicks', 111)
      }
    },
    // 上传组件方法
    handleRemove (file, fileList) {
      // 文件列表移除方法
      this.$emit('handleRemove', file, fileList)
    },
    handlePreview (file) {
      // 点击文件列表中已上传文件时的方法
      this.$emit('handlePreview', file)
    },
    handleExceed (files, fileList) {
      // 文件超出文件限制时的方法
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    beforeRemove (file, fileList) {
      // 删除文件之前时的方法
      return this.$confirm(`确定移除${file.name}？`)
    },
    handleAvatarSuccess (res, file) {
      // 文件上传成功时的方法
      this.$emit('handleAvatarSuccess', res, file)
    },
    // end
    save () {
      this.loading = true
      let formName = 'formData'
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$emit('save', this.formData)
        } else {
          this.loading = false
        }
      })
    },
    submitForm () {
      if (this.buttonRules === true) {
        this.loading = true
        let formName = 'formData'
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$emit('submit', this.formData)
          } else {
            this.loading = false
          }
        })
      }
    },
    restForm () {
      this.$refs['formData'].resetFields()
      // for (let key in this.formData) {
      //   this.formData[key] = ''
      // }
    },
    print () {
      if (this.buttonRules === true) {
        let formName = 'formData'
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$emit('print', this.formData)
          }
        })
      }
    },
    closeLoading () {
      this.loading = false
    },
    restValidate () {
      this.closeLoading()
      this.$refs['formData'].clearValidate()
    },
    rest () {
      this.$refs['formData'].resetFields()
      this.formData = Object.assign({}, this.value)
      let obj = {state: 1}
      this.$emit('reset', obj)
    },
    getValue () {
      this.formData = Object.assign({}, this.value)
    }
  },
  watch: {
    value: {
      handler (cval, oval) {
        this.getValue()
      },
      deep: true
    }
  }
}
</script>

<style lang="scss">
  .hyForm{
    min-height: 100%;
    width: 100%;
    /*background: #fff;*/
  }
  .upload-demo{
    margin-left: 20px;
    width: 90%;
  }
  .yy-form-col{
    text-align: left;
  }
</style>
